<template>
  <VTable ref="tableRef" v-bind="tableOptins">
    <template #form="{ form }">
      <!-- <el-select-v2
        v-model="form.supplierIds"
        placeholder="供应商名称"
        :options="optionsData?.supplierList || []"
        clearable
        filterable
        multiple
        collapse-tags
        :max-collapse-tags="1"
        style="min-width: 200px"
      /> -->
      <XForm
        :fieldList="checkFieldList"
        :formOption="optionsData"
        :formData="form"
      >
        <template #create_user="{ value, input }">
          <VCascader
            key="1"
            :model-value="value"
            @update:model-value="input"
            collapse-tags
            class="w-[200px]"
            placeholder="请输入"
          />
        </template>
        <template #department="{ value, input }">
          <VCascader
            key="2"
            :model-value="value"
            @update:model-value="input"
            collapse-tags
            type="1"
            class="w-[200px]"
            placeholder="事业处"
            :checkStrictly="true"
          />
        </template>
        <!-- <template #supplier="{ value, input }">
          <VSelect
            :model-value="value"
            placeholder="供应商名称"
            :options="optionsData?.supplierList || []"
            @update:model-value="input"
            multiple
            collapse-tags
            style="min-width: 160px"
          />
        </template> -->
      </XForm>
    </template>
    <template #toolbar_btns>
      <VActionBar :actions="actions" />
    </template>
    <template #operation="{ row }">
      <!-- 编辑 -->
      <el-button
        v-hasPermi="[capitalAuthList.payment.bill_detail.check_detail.edit]"
        type="primary"
        link
        @click="handleEdit(row)"
      >
        编辑
      </el-button>
      <!-- 删除 -->
      <el-button
        v-hasPermi="[capitalAuthList.payment.bill_detail.check_detail.delete]"
        type="danger"
        link
        @click="handleDelete(row.id)"
      >
        删除
      </el-button>
      <!-- 日志 -->
      <el-button
        v-hasPermi="[capitalAuthList.payment.bill_detail.check_detail.log]"
        type="primary"
        link
        @click="handleLog(row.id)"
      >
        日志
      </el-button>
    </template>
  </VTable>
  <Add
    v-model="addVisible"
    :data="addData"
    :options="optionsData"
    @refresh="refresh"
    @close="addData = null"
  />
  <VAudit
    v-model="auditVisible"
    title="审核"
    :option="[
      { label: '代付款', value: 0 },
      { label: '已付款', value: 1 },
      { label: '已作废', value: 2 },
    ]"
    url="/check/detail/review"
    :isRemark="false"
    :ids="auditId"
    method="patch"
    @close="auditId = null"
    @refresh="refresh"
  />
  <DerivedCenter ref="DerivedCenterRef"></DerivedCenter>
  <VLog
    v-model="logVisible"
    :autoLoad="false"
    :module="6"
    :id="logId"
    @close="logId = ''"
  />
</template>
<script lang="jsx" setup>
import { ElMessage } from "element-plus";
import { getTableSelectRow } from "@/hooks/tools.js";
import { config_name } from "@/config/export.js";
import XForm from "@/components/XForm/index.vue";
import { checkFieldList } from "../../data.js";
import tagStatus from "@/components/tagStatus/index.vue";
import { getCheckDetailList, deleteCheckDetail } from "../../api.js";
import { transformData } from "@/utils/tools.js";
import Add from "./add/index.vue";
import { capitalAuthList } from "@/Auth/capital.js";
const { proxy } = getCurrentInstance();
const props = defineProps({
  optionsData: { type: Object, default: () => {} },
});
const { optionsData } = toRefs(props);
const tableRef = ref();
const tableOptins = reactive({
  formConfig: {
    data: {
      number: "",
      supplierIds: "",
      user: "",
      departmentIds: "",
      state: "",
      dateRange: { type: "ticketAt", value: [], range: false },
    },
  },

  tooltipConfig: {
    showAll: false,
  },
  isToggle: true,
  columns: [
    {
      type: "checkbox",
      width: 50,
      fixed: "left",
    },
    {
      title: "ID",
      field: "id",
      width: 180,
      slots: {
        default: ({ row }) => {
          return <span>{row?.id?.toString() || "-"}</span>;
        },
      },
      fixed: "left",
    },
    {
      title: "状态",
      slots: {
        default: ({ row }) => {
          return (
            <tagStatus
              code={row?.state}
              type={[
                { label: 0, value: "warning" },
                { label: 1, value: "" },
                { label: 2, value: "danger" },
              ]}
            />
          );
        },
      },
      width: 100,
    },
    {
      title: "支票号",
      field: "checkNo",
      width: 150,
    },
    {
      title: "支票凭证号",
      field: "voucherNo",
      width: 150,
    },
    {
      title: "出票日期",
      field: "ticketAt",
      width: 170,
    },
    {
      title: "供应商名称",
      field: "supplierName",
      width: 100,
    },
    {
      title: "采购制单人",
      field: "procurementMaker",
      width: 100,
    },
    {
      title: "金额/RMB",
      field: "amount",
      width: 100,
    },
    {
      title: "事业处",
      field: "department",
      width: 200,
    },
    {
      title: "移交制单人日期",
      field: "transferProducerAt",
      width: 170,
    },
    {
      title: "密码提供日期",
      field: "passwordProvisionAt",
      width: 170,
    },
    {
      title: "实际汇出/扣款日期",
      field: "debitAt",
      width: 170,
    },
    {
      title: "支付密码",
      field: "paymentPassword",
      width: 100,
    },
    {
      title: "用途",
      field: "checkUse",
      width: 100,
    },
    {
      title: "备注",
      field: "remark",
      width: 200,
    },
    {
      title: "创建时间",
      field: "createdAt",
      width: 170,
    },
    {
      title: "创建人",
      field: "createUser",
      width: 170,
    },
    {
      title: "操作",
      width: 160,
      fixed: "right",
      slots: { default: "operation" },
    },
  ],
  // data: [],
  proxyConfig: {
    props: {
      result: "data",
      total: "total",
    },
    autoLoad: false,
    ajax: {
      query: ({ page, form }) => {
        let params = transformData(form);
        return getCheckDetailList({ ...params, ...page }).then((res) => {
          return {
            data: res.data,
            total: res.total,
          };
        });
      },
    },
  },
});

const refresh = () => {
  tableRef?.value.$table.commitProxy("query");
};
const addData = ref(null);
const addVisible = ref(false);
const handleEdit = (row) => {
  let data = { ...row, id: row.id.toString() };
  addData.value = data;
  addVisible.value = true;
};
const handleDelete = (id) => {
  proxy?.confirm({
    title: "提示",
    content: (
      <p>
        确认删除
        <span class="text-[#3366F1] px-[4px]">{1}</span>
        条数据？
      </p>
    ),
    beforeClose: async (action, instance, done) => {
      if (action === "confirm") {
        try {
          instance.confirmButtonLoading = true;
          instance.confirmButtonText = "处理中..";
          const { code, message } = await deleteCheckDetail({ id });
          if (code !== 200) return ElMessage.success(message);
          ElMessage.success("删除成功!");
        } catch (e) {
          console.error(e);
        } finally {
          instance.confirmButtonLoading = false;
          done();
          refresh();
        }
      } else {
        done();
      }
    },
  });
};
const logVisible = ref(false);
const logId = ref("");
const handleLog = (item) => {
  logId.value = item;
  logVisible.value = true;
};
//审核
const auditVisible = ref(false);
const auditId = ref(null);
const handleAudit = () => {
  let records = tableRef.value?.$table.getCheckboxRecords();
  if (!records?.length) return ElMessage.warning("请至少选择一条数据!");
  //判断state是否含有审核成功
  const isReview = records.some((item) => item.state.value === 1);
  if (isReview) return ElMessage.warning("审核通过的数据不能再审核!");
  const ids = records.map((item) => item.id);
  auditId.value = ids;
  auditVisible.value = true;
};
//导出中心
const DerivedCenterRef = ref();
const handleExport = async () => {
  let condition = getTableSelectRow(tableRef.value);
  DerivedCenterRef.value.open({
    tag_name: config_name["capital"]["check_detail"],
    condition,
  });
};
const actions = [
  {
    label: "新增",
    type: "primary",
    icon: "add1",
    fn: () => {
      addVisible.value = true;
    },
    permission: [capitalAuthList.payment.bill_detail.check_detail.add],
  },
  {
    label: "审核",
    type: "primary",
    fn: handleAudit,
    permission: [capitalAuthList.payment.bill_detail.check_detail.audit],
  },
  {
    label: "导出",
    right: true,
    dkicon: "icon-Upload",
    fn: handleExport,
    permission: [capitalAuthList.payment.bill_detail.check_detail.export],
  },
];
</script>
<style lang="scss" scoped>
.vx-table {
  height: calc(100% - 40px) !important;
}
:deep(.el-tag.el-tag--danger) {
  background-color: var(--base-danger-bg);
}
:deep(.el-tag.el-tag--primary) {
  background-color: var(--base-primary-bg);
  border-color: var(--base-primary-bg);
}
:deep(.el-tag.el-tag--warning) {
  background-color: var(--base-warning-bg);
  border-color: var(--base-warning-bg);
}
</style>
